<?php
/**
 * 用户模块接口
 * User: cqfut
 * Date: 2018/11/1
 * Time: 11:44
 */
//require_once (ROOTDIR."admin/model/csrf_check.php");
require_once ("../../config/path_config.php");
include_once (ROOTDIR."common/base_router.php");
require_once (ROOTDIR."config/sys_config.php");
require_once (ROOTDIR."admin/model/user_model.php");
require_once (ROOTDIR."third_party/PHPExcel.php");

class UserRouter extends BaseRouter {
    public function __construct() {
        parent::__construct();
    }

    function importUsers() {
        $filePath = BaseRouter::doFileUpload("upload_file", ROOTDIR."file/");
        if ( $filePath == NULL ) {
            return;
        }
        $objPHPExcel = PHPExcel_IOFactory::load($filePath);
        $sheet = $objPHPExcel->getActiveSheet();
        $userCnt = $sheet->getHighestRowAndColumn()['row'];
        /*
         * excel 文件格式如下:
         * A - 用户名
         * B - 姓名
         * C- 年级
         * D - 班级
         * E - 校区
         */
        $createrId = BaseRouter::getSession('user_id');
        $model = new UserModel();
        for ( $i = 2; $i <= $userCnt; $i++) {
            $userid = $sheet->getCell('A'.$i)->getValue();
            $name = $sheet->getCell('B'.$i)->getValue();
            $gradestr = $sheet->getCell('C'.$i)->getValue();
            $classstr = $sheet->getCell('D'.$i)->getValue();
            preg_match("/([0-9]+)/i", $classstr, $match);
            $class = intval($match[1]);
            $school = $sheet->getCell('E'.$i)->getValue();
            $phone  = $sheet->getCell('F'.$i)->getValue();
            // 1 - 学生, 2 - 老师 3 - 学生家长
            $type  = $sheet->getCell('G'.$i)->getValue();
            if ($type == null ) {
                $type = 1;
            }
            $inZuoZhu = $sheet->getCell('G'.$i)->getValue();
            $inZuoZhu = intval($inZuoZhu);

            // 自动重命令userid
            $k = 1;
            $oldUserId = $userid;
            while ( $model->isExist($userid) > 0 ) {
                $userid = $oldUserId.$k;
                $k ++;
            }
            // 添加用户到数据库
            $ret = $model->addUser($userid, $name, $school, -1,
                $type, $inZuoZhu, -1, -1, $phone,
                $gradestr, $class, $createrId);
        }
        $this->setRspStatus(1, 0,"导入用户信息完毕");
    }

    function exportUsers() {
        // 权限验证
        $createrId = BaseRouter::getSession('user_id');
        // 除administrator以外，其他用户都只允许导出自己创建的用户
        if (  BaseRouter::getSession('administrator') != null
            || BaseRouter::getSession('jgadmin') != null ) {
            $createrId = null;
        }

        // 生成导出文件
        $keyWord = $this->getReqStrVal('keyword');
        $userType = $this->getReqIntVal('type'); // 老师/学生
        $grade = $this->getReqStrVal('grade'); // 年级
        $class = $this->getReqIntVal('class'); // 班级
        $beginDate = $this->getReqStrVal('begin_date'); // 年级
        $endDate = $this->getReqStrVal('end_date'); // 年级

        // 机构特有属性
        $isInZuoZhu = $this->getReqIntVal('inzuozhu'); // 是否在机构
        $userStatus = $this->getReqIntVal('status'); // 试听
        $vendor = $this->getReqStrVal('vendor'); // 提供给谁使用 school 或机构

        $objPHPExcel = new PHPExcel();

        // 设置文件属性
        $objPHPExcel->getProperties()->setCreator("Maarten Balliauw")
            ->setLastModifiedBy("Maarten Balliauw")
            ->setTitle("Office 2007 XLSX Test Document")
            ->setSubject("Office 2007 XLSX Test Document")
            ->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
            ->setKeywords("office 2007 openxml php")
            ->setCategory("Test result file");

        // 添加excel文件标题
        $objPHPExcel->setActiveSheetIndex(0);
        $objPHPExcel->getActiveSheet()
            ->setCellValue('A1', '用户名')
            ->setCellValue('B1', '姓名')
            ->setCellValue('C1', '年级')
            ->setCellValue('D1', '班级')
            ->setCellValue('E1', '学校')
            ->setCellValue('F1', '创建时间');

        // 添加excel文件中的数据
        $model = new UserModel();
        $pageId = 0;
        $lineIdx = 2;
        while(1) {
            $beginIdx = $pageId * SysConfig::$PAGESIZE;
            $userList = $model->getUserList(
                $keyWord, $userType,$grade, $class, $isInZuoZhu, $userStatus,
                $beginIdx, SysConfig::$PAGESIZE,
                $vendor, $beginDate, $endDate, $createrId);
            if ( count($userList) <= 0 ) {
                break;
            }

            foreach ( $userList as $user ) {

                $objPHPExcel->getActiveSheet()
                    ->setCellValue('A'.$lineIdx, $user['id'])
                    ->setCellValue('B'.$lineIdx, urldecode($user['name']))
                    ->setCellValue('C'.$lineIdx, urldecode($user['gradestr']));
                if ( $user['class'] > 0 ) {
                    $objPHPExcel->getActiveSheet()
                        ->setCellValue('D'.$lineIdx, $user['class'].'班' );
                }
                $objPHPExcel->getActiveSheet()
                    ->setCellValue('E'.$lineIdx, urldecode($user['school']) )
                    ->setCellValue('F'.$lineIdx, $user['createtime']);
                $lineIdx ++;
            }
            $pageId ++;
        }

        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="user_export.xlsx"');
        header('Cache-Control: max-age=0');
        header('Cache-Control: max-age=1');
        header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
        header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
        header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
        header ('Pragma: public'); // HTTP/1.0
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
        $objWriter->save('php://output');
    }

    function getGradeList() {
        $model = new UserModel();
        $gradeList = $model->getGradeList();
        $this->setRspData($gradeList);
    }

    function getUserList() {
        $keyWord = $this->getReqStrVal('keyword');
        $userType = $this->getReqIntVal('type'); // 老师/学生
        $grade = $this->getReqStrVal('grade'); // 年级
        $class = $this->getReqIntVal('class'); // 班级

        // 机构特有属性
        $isInZuoZhu = $this->getReqIntVal('inzuozhu'); // 是否在机构
        $userStatus = $this->getReqIntVal('status'); // 试听
        $vendor = $this->getReqStrVal('vendor'); // 试听

        $pageId = $this->getReqIntVal('pageid');
        if ( $pageId < 0 ) {
            $pageId = 0;
        }
        $beginIdx = $pageId * SysConfig::$PAGESIZE;
        $model = new UserModel();
        // 获取用户的数量
        $cnt = $model->getUserCnt($keyWord, $userType,$grade, $class, $isInZuoZhu, $userStatus);
        $maxPageId = floor($cnt/SysConfig::$PAGESIZE);
        // 获取所有用户的用户列表
        $userList = $model->getUserList($keyWord, $userType,$grade, $class,
            $isInZuoZhu, $userStatus,
            $beginIdx, SysConfig::$PAGESIZE, $vendor);

        // 判断是否具有所有用户的编辑权限
        $allowEditAll = false;
        if (  BaseRouter::getSession('jgadmin') != null
            || BaseRouter::getSession('administrator') != null ) {
            $allowEditAll = true;
        }

        $userId = BaseRouter::getSession('user_id');
        $idx = 0;
        foreach ( $userList as $user ) {
            $userList[$idx]['can_op'] = 0;
            if ( $allowEditAll ) {
                $userList[$idx]['can_op'] = 1;
            }
            else if ( $user['creater_id'] == $userId ) {
                $userList[$idx]['can_op'] = 1;
            }
            $idx ++;
        }

        $this->setRspVal('user_list', $userList);
        $this->setRspVal('max_pageid', $maxPageId);
        $this->setRspVal('total_cnt', $cnt);
    }
    function addUser() {
        $args = array();
        array_push($args, 'id', 'name', 'school', 'status', 'type');
        // 必要参数判断
        if ( ! $this->checkParam($args) ) {
            $this->setRspStatus(0, -2,"缺少必要字段" );
            return;
        }
        $id = $this->getReqStrVal('id');
        $name = $this->getReqStrVal('name');
        $school = $this->getReqStrVal('school');
        $status = $this->getReqIntVal('status');
        $type = $this->getReqIntVal('type');
        $inzuozhu = $this->getReqIntVal('inzuozhu');
        $grade = $this->getReqIntVal('grade');
        $upordown = $this->getReqIntVal('upordown');
        $phone = $this->getReqStrVal('phone');
        $gradestr = $this->getReqStrVal('gradestr'); // 初2019级
        $class = $this->getReqIntVal('class'); // 2 - 2班
        $model = new UserModel();

        // 判断用户是否已存在
        if ( $model->isExist($id) > 0 ) {
            $this->setRspStatus(0, -1,"用户已存在" );
            return;
        }

        $createrId = BaseRouter::getSession('user_id');
        $ret = $model->addUser($id, $name, $school, $status,
            $type, $inzuozhu, $grade, $upordown, $phone,
            $gradestr, $class, $createrId);
        if ( $ret >= 0 ) {
            $this->setRspStatus(1, 0,"添加用户信息成功" );
        }
        else {
            $this->setRspStatus(0, -1,"数据库错误" );
        }
    }

    function editUser() {
        $args = array();
        array_push($args, 'id', 'name', 'school', 'type');
        // 必要参数判断
        if ( ! $this->checkParam($args) ) {
            $this->setRspStatus(0, -2,"缺少必要字段" );
            return;
        }

        $createrId = null;
        // 判断是否具有所有用户的编辑权限
        if (  BaseRouter::getSession('jgadmin') == null
            && BaseRouter::getSession('administrator') == null ) {
            $createrId = BaseRouter::getSession('user_id');
        }

        $id = $this->getReqStrVal('id');
        $name = $this->getReqStrVal('name');
        $school = $this->getReqStrVal('school');
        $status = $this->getReqIntVal('status');
        $type = $this->getReqIntVal('type');
        $inzuozhu = $this->getReqIntVal('inzuozhu');
        $grade = $this->getReqIntVal('grade'); // 表示年级的数字，旧版
        $upordown = $this->getReqIntVal('upordown');
        $phone = $this->getReqStrVal('phone');
        $gradestr = $this->getReqStrVal('gradestr'); // 初2019级
        $class = $this->getReqIntVal('class'); // 2 - 2班

        $model = new UserModel();

        // 系统管理员administrator不允许被编辑
        if ( $model->isAdmin($id) > 0 ) {
            $this->setRspStatus(0, -1,"权限错误" );
            return;
        }

        // 非 jgadmin 和 administrator 只能编辑自己创建的用户
        $ret = $model->editUser($id, $name, $school, $status,
            $type, $inzuozhu, $grade, $upordown, $phone,
            $gradestr, $class, $createrId);
        if ( $ret > 0 ) {
            $this->setRspStatus(1, 0,"修改用户信息成功" );
        }
        else {
            $this->setRspStatus(0, -1,"数据库错误" );
        }
    }

    function delUser() {
        $args = array();
        array_push($args, 'userids');
        // 必要参数判断
        if ( ! $this->checkParam($args) ) {
            $this->setRspStatus(0, -2,"缺少必要字段" );
            return;
        }

        $userIds = $this->getReqVal('userids');
        $model = new UserModel();

        $createrId = null;
        // 判断是否具有删除除管理员以外所有用户的权限
        if ( BaseRouter::getSession('jgadmin') == null
            && BaseRouter::getSession('administrator') == null ) {
            $createrId = BaseRouter::getSession('user_id');
        }

        // 依次删除所选用户
        $errMsg = "";
        $errCode = 0;
        $status = 1;
        foreach ( $userIds as $id ) {
            // 用户不存在
            if ( $model->isExist($id) <= 0 ) {
                continue;
            }
            // 用户是管理员用户
            if ( $model->isAdmin($id) > 0 ) {
                $errMsg = "不具备删除该用户的权限";
                $errCode = -1;
                $status = 0;
                break;
            }
            // 非jgadmin和administrator只能删除自己创建的用户
            $ret = $model->delUser($id, $createrId);
            if ( $ret <= 0 ) {
                $errMsg = "数据库错误";
                $errCode = -2;
                $status = 0;
                break;
            }
        }
        $this->setRspStatus($status, $errCode, $errMsg );
    }

    public function checkPrivileges() {
        $priviNames = $this->getReqVal('privi_names');
        $heckRes = array();
        foreach ( $priviNames as $pname ) {
            $checkCode = BaseRouter::getSession($pname) != null;
            $heckRes[$pname] = $checkCode;
        }
        $this->setRspData($heckRes);
    }

    public function run() {
        $op = $this->getReqVal('op');
        if ( $op == 'add' ) {
            $this->addUser();
        }
        else if ( $op == 'del' ) {
            $this->delUser();
        }
        else if ( $op == 'edit' ) {
            $this->editUser();
        }
        else if ( $op == 'search' ) {
            $this->getUserList();
        }
        else if ( $op == 'check' ) {
            $this->checkPrivileges();
        }
        else if ( $op == 'get_grade_list') {
            $this->getGradeList();
        }
        else if ( $op == 'import') {
            $this->importUsers();
        }
        else if ( $op == 'export') {
            $this->exportUsers();
        }
        else {
            $this->setRspStatus(0, -1,"参数错误" );
        }
    }
}

$router = new UserRouter();
$privilegeNames = array('administrator', 'jgadmin', 'xxadmin');
if ( ! $router->checkAuth($privilegeNames) ) {
    $router->setRspStatus(0, -1001,"不具备该权限");
    $router->finish();
    exit(1);
}
$router->init();
$router->run();
$router->finish();